<template>
  <div>
    <el-form ref="form" :model="form" inline size="mini" :rules="rules" :disabled="this.type1==='detail'" label-width="90px">
      <el-collapse v-model='model'>
        <div class="tableHead">
          <div class="tabletitle">用户权限编辑</div>
          <div class="btnGroup">
            <el-button-group>
              <template slot-scope="scope">
                <el-button @click="changePassword('职位模板')" size="mini" type="primary" :disabled="isDisables"  icon="el-icon-edit">职位模板</el-button>
                <el-button type="primary" size="mini" icon="el-icon-edit" :disabled="isDisables"  @click="changePassword('修改密码')">修改密码</el-button>
              </template>
            </el-button-group>
          </div>
        </div>
        <div class="searchform">
          <el-form-item label="员工编号" prop="employeeNo">
            <el-input v-model="form.employeeNo" disabled="disabled" class="search-input" placeholder="员工编号" />
          </el-form-item>
          <el-form-item label="账号" prop="userCode">
            <el-input v-model="form.userCode" :disabled="userCodeShow" class="search-input" placeholder="账号" />
          </el-form-item>
          <el-form-item label="姓名" prop="employeeName">
            <el-input v-model="form.employeeName" disabled="disabled" class="search-input" placeholder="姓名" />
          </el-form-item>
          <!-- <el-form-item prop="userState" label="用户状态">
            <r-select v-model="userStatus1" type='1003' class='search-input'></r-select>
          </el-form-item> -->
          <!--20190826注释
             <el-form-item label="职责" prop="employeeRoles">
            <el-checkbox-group v-model="checkedList">
              <el-checkbox v-for="role in sites" :label="role.codeId" :key="role.codeId" style="margin-right:10px" :value="role.codeId">
                {{role.codeCnDesc}}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item> -->
        </div>
        <!-- 职责 -->
        <el-collapse-item name="2" title="职责">
          <!-- <div class='duty'>职责</div> -->
          <el-checkbox-group v-model="checkedList" :disabled="isDisables" style="margin:10px 0 10px 20px;">
            <el-checkbox v-for="role in sites" :label="role.codeId" :key="role.codeId+'C'" :value="role.codeId">{{role.codeCnDesc}}</el-checkbox>
          </el-checkbox-group>
        </el-collapse-item>
        <!-- 权限管理 -->
        <el-collapse-item name="1" title="权限管理">
          <el-row style="display:flex;flex-direction: column">
            <el-row style="height: 495px">
              <el-col style="height: 450px;width: 33%;">
                <div class='menu-header'>菜单权限</div>
                <el-scrollbar style="height: 450px;border: 1px solid rgba(144,147,153,.5);">
                  <el-col style="padding: 5px 3px;">
                    <el-tree ref="tree" 
                    style="margin-top: 12px;" 
                    v-loading="loading" 
                    show-checkbox 
                    :data="jsonTree"
                    node-key="id" 
                    highlight-current 
                    @node-click="nodeClickHandle" 
                    :expand-on-click-node="false" 
                    />
                  </el-col>
                </el-scrollbar>
              </el-col>
              <el-col style="height: 450px;width: 33%;">
                <div class='menu-header'>客户信息操作权限 </div>
                <el-scrollbar style="height: 450px;border: 1px solid rgba(144,147,153,.5);border-left: none;border-right: none;">
                  <el-col style="padding: 5px 3px;">
                    <div>
                      <div v-loading="rangeloading">
                        <div><label>操作权限</label></div>
                        <el-checkbox-group v-model="roleMenuRange" @change="handleRoleMenuRangeChange">
                          <div style="margin:0px 0px 0px 20px;width:20px;">
                            <el-checkbox v-for="menuRange in objRange" :label="menuRange.menuRangeId" :key="menuRange.menuRangeId"
                              :value="menuRange.menuRangeId">{{menuRange.codeCnDesc}}</el-checkbox>
                          </div>
                        </el-checkbox-group>
                        <!-- <el-radio-group v-model="roleMenuRange" @change="handleRoleMenuRangeChange">
                          <div style="margin:0px 0px 0px 20px;width:20px;">
                            <el-radio v-for="menuRange in objRange" 
                            :label="menuRange.menuRangeId" 
                            :key="menuRange.menuRangeId"
                            :value="menuRange.menuRangeId">{{menuRange.codeCnDesc}}
                            </el-radio>
                          </div>
                        </el-radio-group> -->
                      </div>
                      <br />
                      <div v-loading="actionloading">
                        <div><label>操作按钮</label></div>
                        <el-checkbox-group v-model="roleMenuAction"  @change="handleRoleMenuActionChange">
                          <div style="margin:0px 0px 0px 20px;width:20px;">
                            <el-checkbox v-for="menuAction in objAction" :label="menuAction.menuCuringId" :key="menuAction.menuCuringId"
                              :value="menuAction.menuCuringId">{{menuAction.actionName}}</el-checkbox>
                          </div>
                        </el-checkbox-group>
                      </div>
                    </div>
                  </el-col>
                </el-scrollbar>
              </el-col>
              <el-col style="height: 450px;width: 33%;">
                <div class='menu-header'>个人参数配置</div>
                <el-scrollbar style="height: 450px;border: 1px solid rgba(144,147,153,.5);">
                  <el-col style="padding: 5px 3px;">
                    <div>
                      <div>
                        <Todo ref="Todo"></Todo>
                      </div>
                      <div>
                        <part ref="part"></part>
                      </div>
                      <div>
                        <storageVec ref="storageVec"></storageVec>
                      </div>
                      <div>
                        <storagePart ref="storagePart"></storagePart>
                      </div>
                      <div>
                        <storageJpck ref="storageJpck"></storageJpck>
                      </div>
                      <div>
                        <favorableModels ref="favorableModels"></favorableModels>
                      </div>
                      <!-- 结算 -->
                      <div>
                        <settlement ref="settlement">123</settlement>
                      </div>
                    </div>
                  </el-col>
                </el-scrollbar>
              </el-col>
            </el-row>
            <el-row style="text-align: center;margin-bottom: 15px;">

              <el-button type="primary" v-show="this.type1 == 'edit'" @click="reqAuth">确 定</el-button>
              <el-button @click='closeDialog()'>取 消</el-button>
            </el-row>
          </el-row>
        </el-collapse-item>
      </el-collapse>
    </el-form>
    <!-- 修改密码 -->
    <BaseDialog :visible.sync="visible" :title="title" destroyOnClose>
        <FormPanel
        v-if="title == '修改密码'?true:false"
        ref="formPanel"
        :cols="2"
        :labelWidth="110"
        :list="formList"
        formType="add"
        :isSubmitBtn="true"
        @formChange="formChangeHandle"
        style="margin-top: 20px"
      />
      <div v-else>
        <positionTemplate @cancleHandle="cancleHandle"></positionTemplate>
      </div>
    </BaseDialog>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import { dictionary } from '@/utils/dictMixin';
import {
  userDataVue,
  findByEmployeeId,
  findEmployeeRoleById,
  findTcCodeByType,
  savePermission,
  supereditpassword,
  } from '@/api/common/auth/employeeAuth';
import * as types from '@/api/common/auth/roleManage/types';
import { getJsonTree,codeCheck } from '@/utils/index';
import Todo from '@/pages/common/auth/roleManage/components/TodoList/Todo.vue'
import part from '@/pages/common/auth/roleManage/components/TodoList/part.vue'
import storageVec from '@/pages/common/auth/roleManage/components/TodoList/storageVec.vue'
import storagePart from '@/pages/common/auth/roleManage/components/TodoList/storagePart.vue'
import storageJpck from '@/pages/common/auth/roleManage/components/TodoList/storageJpck.vue'
import favorableModels from '@/pages/common/auth/roleManage/components/TodoList/favorableModels.vue'
import settlement from '@/pages/common/auth/roleManage/components/TodoList/settlement.vue'

import _ from 'lodash';
import positionTemplate from './positionTemplate'
export default {
  name: 'Employeeauthpanel',
  mixins: [dictionary],
  components: {
    Todo,
    part,
    storageVec,
    storagePart,
    storageJpck,
    favorableModels,
    positionTemplate,
    settlement
  },
  props: {
    rowData: {
      type: Object,
      default: () => ({})
    },
    type1: {
      type: String,
      default: 'edit'
    }
  },
  data() {
    this.saveData = null;
    this.checkListRoleMenuRange = [];
    this.checkListRoleMenuAction = [];
    return {
      formList: this.createFormList(),
      title:'',
      loading: false,
      rangeloading: false,
      actionloading: false,
      isDisables:true,
      visible: false,
      tree: [],
      menuId: '',
      objRange: [],
      roleMenuAction: [],
      roleMenuRange: [],
      objAction: [],
      model: ["1",'2'],
      userCodeShow: true,
      checkedList:[],
      sites:[],
      form: {},
      jsonTree:[],
      isRoleMenuRange:false,
      defaultProps: {
          children: 'children',
          label: 'label'
        },
      rules: {
        userCode: [{
          required: true,
          message: "请输入账号",
          trigger: "blur"
        },
        {trigger: "blur",validator: codeCheck}
        ]
      },
    }
  },
  computed: {
    ...mapState('app', ['btnLoading']),
    
    // addBtnState() {
    //   return this.btnLoading[types.YAN_ROLE_ADD];
    // }
  },
  created() {
    this.searchTree();
    
  },
  methods: {
    createFormList() {
      return [
        {
          type: 'INPUT',
          label: '账号',
          disabled: true,
          fieldName: 'userCode',
          placeholder: '请输入',
          initialValue: '',
        },
        {
          type: 'INPUT',
          label: '姓名',
          fieldName: 'employeeName',
           disabled: true,
          placeholder: '请输入',
          initialValue: '',
        },
        {
          type: 'INPUT',
          label: '新密码',
          fieldName: 'newPassword',
          placeholder: '请选择',
          rules: [{ required: true, message: '请输入新密码', trigger: 'change' }, { min: 8, max: 15, message: '长度在 8 到 15 个字符', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '确认密码',
          fieldName: 'confirmPassword',
          placeholder: '请选择',
          rules: [{ required: true, message: '请确认新密码', trigger: 'change' }, { min: 8, max: 15, message: '长度在 8 到 15 个字符', trigger: 'blur' }]
        }
      ];
    },
    //加载树
    async searchTree() {
      if(this.type1 == 'edit'){
        this.isDisables=false
      }

      this.loading = true;
      // let param = `employeeId=${this.rowData.employeeId}&dataSource=${this.rowData.dataSources}`;
      let param = `${this.rowData.employeeId}/${this.rowData.dataSources}`;
      const res = await userDataVue(param);
      // const resRole = await roleData(this.rowData.employeeId)
      let restree = res.data
      console.log(restree,"restree")
      //刷新权限管理---treejson找不到--by20190830
      this.refreshMenut(restree);
      const employeeRes = await findByEmployeeId(this.rowData.employeeId);
      this.form = _.cloneDeep(employeeRes.data);
      if (employeeRes.data.userCode === null) {
        this.userCodeShow = false;
      }
      //职责复选框选中数据
      this.employeeRolesCheck(this.rowData.employeeId);

      this.deleteRes(res.data.treejson);
      this.tree = res.data.treejson;
      this.loading = false;
      // 加载树
      this.getJsonTreeData()
    },
    getJsonTreeData() {
      this.tree.forEach(el => (el.label = el.text));
      this.tree.forEach(el => (el.parentId = el.parent));
      this.jsonTree=getJsonTree(this.tree)
      this.jsonTree=_.unionBy(this.jsonTree, 'id')
      // return getJsonTree(this.tree);
    },
    refreshMenut(restree) {
      /**
        * 勾选菜单
        */
      let restreejson = restree.treejson;
      let selectedmenu = []
      for (let j = 0; j < restreejson.length; j++) {
        let states = restreejson[j].state
        if (states.checked == true) {
          selectedmenu.push(restreejson[j].id)
        }
      }
      this.$refs['tree'].setCheckedKeys(selectedmenu)
      // 操作权限操作按钮
      this.checkListRoleMenuRange = restree.treeMenuRange
      this.checkListRoleMenuAction = restree.treeMenuAction
    },
    //职责复选框查询
    employeeRolesCheck(id) {
      const type = 1006;
      /*页面提示未定义。注释于20190826 
      this.getEmployeeRoles(type); */
      // const checkedLists = [];
      this.checkedList=[]
      findTcCodeByType(type)
        .then(res => {
          this.sites=res.data
          res.data.forEach(ele=>{
            this.checkedList.push(ele.codeId)
          })
          console.log(res.data,this.checkedList,"res")
          
         /*  for (let i = 0; i < res.length; i++) {
            checkedLists.push(res[i].codeId);
          }
          this.checkedList = checkedLists; */
        })
        .catch(err => {
          //table.complete()
        });
    },
    // 删除无效数据(无父节点)
    deleteRes(res) {
      let result = [];
      for (let i = 0; i < res.length && res[i].id != null; i++) {
        let pid = res[i].parent;
        let oid = res[i].id;
        result[oid] = pid;
      }
      for (let j = 0; j < res.length; j++) {
        // 一级父节点跳过
        if (res[j].parent == "#") continue;
        if (res[j] && result[res[j].parent] == null) {
          let index = j;
          j = 0;
          delete result[res[index].id];
          res.splice(index, 1);
        }
      }
    },
    //树点击
    nodeClickHandle(data) {
      let {
        id,
        parent,
        text
      } = data
      this.text = text
      this.searchMenuHandle(id)
    },
    //显示客户信息操作权限
    async searchMenuHandle(id) {
      // this.rangeloading = true
      // this.actionloading = true
      this.menuId=id;
      const getRoleMenuRangeRes = await getRoleMenuRange(id, this.rowData.roleId)
      this.objRange = _.cloneDeep(getRoleMenuRangeRes.data)
      this.roleMenuRange="";
      if(this.checkListRoleMenuRange!=null){
        /* for(let i=0;i<this.checkListRoleMenuRange.length;i++){
          console.log(this.checkListRoleMenuRange[i].split("-")[0],"权限配置单选1")
          if(id===this.checkListRoleMenuRange[i].split("-")[0]){
            console.log(this.checkListRoleMenuRange[i].split("-")[1],"权限配置单选2")
            this.roleMenuRange=Number(this.checkListRoleMenuRange[i].split("-")[1]);
          }
        } */
        for(let i=0;i<this.checkListRoleMenuRange.length;i++){
          if(id===this.checkListRoleMenuRange[i].split("-")[0]){
            let rangArray=this.checkListRoleMenuRange[i].split("-")[1].split(",");
            for(let j=0;j<rangArray.length;j++){
              this.roleMenuRange.push(Number(rangArray[j]));
            }
            return;
          }
        }
      }
      const getRoleMenuActionRes = await getRoleMenuAction(id, this.rowData.roleId)
      this.objAction = _.cloneDeep(getRoleMenuActionRes.data)
      this.roleMenuAction=[];
      if(this.checkListRoleMenuAction!=null){
        for(let i=0;i<this.checkListRoleMenuAction.length;i++){
          if(id===this.checkListRoleMenuAction[i].split("-")[0]){
            let actionArray=this.checkListRoleMenuAction[i].split("-")[1].split(",");
            for(let j=0;j<actionArray.length;j++){
              this.roleMenuAction.push(Number(actionArray[j]));
            }
            return;
          }
        }
      }
      this.rangeloading = false
      this.actionloading = false
    },
    //操作权限改变事件
    handleRoleMenuRangeChange(value){
        /* this.checkListRoleMenuRange=[]
        this.checkListRoleMenuRange.push(this.menuId+"-"+value); */
      if(this.checkListRoleMenuRange!=null && this.checkListRoleMenuRange.length>0){
        let ok=true;
        for(let i=0;i<this.checkListRoleMenuRange.length;i++){
          if(this.menuId===this.checkListRoleMenuRange[i].split("-")[0]){
            if(value.length==0){
              this.checkListRoleMenuRange.splice(i,1);
            }else{
              this.checkListRoleMenuRange[i]=this.menuId+"-"+value.join(",");
            }
            if(value.length > 1){
              this.$message({
                type: "info",
                message: "请单选!"
              });
            }
            /* if(value.length== 1){
              this.checkListRoleMenuRange[i]=this.menuId+"-"+value.join(",");
            }else{
              this.checkListRoleMenuRange.splice(i,1);
              this.checkListRoleMenuRange=[]
              this.$message({
                type: "info",
                message: "请单选!"
              });
            } */
            ok=false;
            return;
          }
        }
        if(ok){
          this.checkListRoleMenuRange.push(this.menuId+"-"+value.join(","));
        }
      }else{
        this.checkListRoleMenuRange=[];
        this.checkListRoleMenuRange.push(this.menuId+"-"+value.join(","));
      }
    },
    //操作按钮改变事件
    handleRoleMenuActionChange(value){
      if(this.checkListRoleMenuAction!=null && this.checkListRoleMenuAction.length>0){
        let ok=true;
        for(let i=0;i<this.checkListRoleMenuAction.length;i++){
          if(this.menuId===this.checkListRoleMenuAction[i].split("-")[0]){
            if(value.length==0){
              this.checkListRoleMenuAction.splice(i,1);
            }else{
              this.checkListRoleMenuAction[i]=this.menuId+"-"+value.join(",");
            }
            ok=false;
            return;
          }
        }
        if(ok){
          this.checkListRoleMenuAction.push(this.menuId+"-"+value.join(","));
        }
      }else{
        this.checkListRoleMenuAction=[];
        this.checkListRoleMenuAction.push(this.menuId+"-"+value.join(","));
      }
    },
    //分配权限保存
    async reqAuth() {
      console.log("reqAuth")
      if(this.checkListRoleMenuRange instanceof Array && this.checkListRoleMenuRange.length > 0){
        this.checkListRoleMenuRange.forEach(x=>{
            if(x.indexOf(",") > 0){
              this.isRoleMenuRange =false
            }else{
              this.isRoleMenuRange =true
            }
        })
      }else{
        this.isRoleMenuRange =true
      }
      
      if(this.isRoleMenuRange){
        let selectedHalfNode = this.$refs['tree'].getCheckedKeys() //父节点
        let selectedNode = this.$refs['tree'].getHalfCheckedKeys() //子节点
        let allNode = selectedHalfNode.concat(selectedNode)
        if (allNode == '') {
          this.$message({
            type: "info",
            message: "请至少分配一条权限!"
          });

        } else {
          //去掉一级菜单
          for (var k = 0; k < allNode.length; k++) {
            var nodekv = allNode[k]
            if (nodekv.length == 2) {
              allNode.splice(k, 1)
            }
          }
          let params = {
            checkedList:this.checkedList,
            roleId: this.rowData.roleId,
            nowTree: allNode.join(','),
            treeMenuRange: this.checkListRoleMenuRange.join(';'),
            treeMenuAction: this.checkListRoleMenuAction.join(';'),
            nowRole: this.rowData.roleId,
            maintain: this.$refs.Todo.getData(),
            accessories: this.$refs.part.getData(),
            vehicleWarehouse: this.$refs.storageVec.getData(),
            accessoriesWarehouse: this.$refs.storagePart.getData(),
            suppliesWarehouse: this.$refs.storageJpck.getData(),
            favorableModels: this.$refs.favorableModels.getData(),
            checkedSettlementList:this.$refs.settlement.getData(),
          }
          this.$refs['tree'].setCheckedKeys(selectedHalfNode)
          //const setRoleAuthRes = await setRoleAuth(this.rowData.roleId, params)
          console.log(this.rowData,params,"this.rowData.roleId")
          const setRoleAuthRes = await savePermission(params)
          if(setRoleAuthRes.resultCode == 200) {
            this.$notify.success({title: '提示信息',message:'保存成功!'});
            this.closeDialog('refresh');
          }else {
            this.$notify.error({title: '提示信息',message:setRoleAuthRes.errMsg||'保存失败!'});
            this.closeDialog()
          }
        }
      }else{
        this.$message({
          type: "info",
          message: "客户信息中的操作权限请单选!"
        });
     }
    },
    //formChangeHandle
     formChangeHandle(val) {
       let that=this
       if(val.newPassword != undefined){
          if(val.newPassword == val.confirmPassword ){
            console.log(val,"val")
            let data={
              employeeId:that.form.employeeId,
              userCode:val.userCode,
              newPassword:val.newPassword
            }
            console.log(data,"data")
            supereditpassword(data).then(res => {
              if(res.resultCode == 200){
                this.$message({
                  type: 'success',
                  message: "修改成功"
                })
                that.cancleHandle()
              }else{
                this.$message({
                  type: 'info',
                  message: res.errMsg
                })
              }
            })
            .catch(err => {})
          }else{
            this.$message({
                message: '两次密码不一样',
                type: 'warning'
              });
          }
       }
      
    },
    //修改密码
    changePassword(data){
      this.visible=true
      this.title=data
      this.formList[0].initialValue=this.form.userCode
      this.formList[1].initialValue=this.form.employeeName      
    },
    //关闭
    cancleHandle(data,dataTree){
      this.visible=data
      dataTree.forEach(el => (el.label = el.text));
      dataTree.forEach(el => (el.parentId = el.parent));
      this.jsonTree=getJsonTree(dataTree)
      this.jsonTree=_.unionBy(this.jsonTree, 'id')
    },
    //返回
    closeDialog(type) {
      this.$emit('close', false, type);
    },
    rolePermission() {

    }
  }
};
</script>

<style lang="less" scoped>
  .el-checkbox+.el-checkbox {
    margin-left: 0px;
  }

  .el-checkbox {
    margin-right: 25px;
  }
  .duty{
    width: 99%;
    height: 30px;
    line-height: 30px;
    margin-bottom: 5px;
    background: #eee;
    text-indent: 5px;
  }
  .menu-header {
    height: 30px;
    line-height: 30px;
    margin-bottom: 5px;
    background: #eee;
    text-indent: 5px;
  }

  .app-container .el-dialog__body {
    padding: 0 20px;
  }
</style>
